package com.crm.service.System;

import com.crm.common.BusinessException;
import com.crm.dao.SystemMapper;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.http.HttpHeaders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import static org.springframework.util.ObjectUtils.isEmpty;

@Service
public class SystemImpl implements Systeminface {
    private static final Logger log = LoggerFactory.getLogger(SystemImpl.class);

    @Autowired
    private SystemMapper systemMapper;

    @Override
    public void CheckVersion(HttpServletResponse response,String version) {
        int ver = 100;
        File file = null;
        FileInputStream fileInputStream= null;
        response.reset();
//        response.setCharacterEncoding("UTF-8");
        OutputStream out = null;
        try {
            String path = System.getProperty("user.dir") + "\\app-release.apk";
            log.info(path);
            file = ResourceUtils.getFile(path);
            fileInputStream = new FileInputStream(file);
            out = response.getOutputStream();
            response.setHeader(HttpHeaders.CONTENT_TYPE,"application/octet-stream");
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION,"attachment;filename=app-release.apk");
            response.setHeader(HttpHeaders.CONTENT_LENGTH,String.valueOf(file.length()));
            response.setHeader("Accept-Ranges", "bytes");
            IOUtils.copy(fileInputStream,out);
//            response.getOutputStream().write(fileInputStream.readAllBytes());

            log.info("Download successfully!");
        } catch (FileNotFoundException e) {
            throw new BusinessException(201,"读取最新app失败");
        } catch (IOException e) {
            throw new BusinessException(202,"发送app失败");
        } finally {
            try {
                if (out != null) {
                    out.flush();
                    out.close();
                }
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
            } catch (IOException e) {
                log.error("关闭流发生异常", e);
            }
        }
    }


}
